<template>
  <div class="main-box">
    <TreeFilter label="data" id="attr" :data="treeFilterData" @change="changeTreeFilter" />
    <div class="table-box">
      <ProTable
        ref="proTable"
        row-key="id"
        :indent="20"
        :columns="columns"
        :request-api="getTableList"
        :request-auto="true"
        :init-param="initParam"
        :data-callback="dataCallback"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button type="primary" :icon="CirclePlus" plain @click="batchSelectUser(scope.selectedList)">
            确定选中资产
          </el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link @click="selectOneUser(scope.row)">
            <el-icon style="vertical-align: middle">
              <Select />
            </el-icon>
            选择
          </el-button>
        </template>
      </ProTable>
    </div>
  </div>
</template>

<script setup lang="tsx" name="treeProTable">
import { onMounted, reactive, ref } from "vue";
import { User } from "@/api/interface";
import { genderType } from "@/utils/dict";
import { useHandleData } from "@/hooks/useHandleData";
import { ElMessage, ElNotification } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "@/views/proTable/components/UserDrawer.vue";
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { getUserTreeList, deleteUser, editUser, addUser, getUserStatus, getUserDepartment } from "@/api/modules/user";
import { findUserTreeList } from "@/api/modules/jggl";
import { getConfigurationCategoryTreeAllData } from "@/api/modules/slaProtocolManagement";
import { cItemsFind } from "@/api/modules/dataDictionary";
onMounted(() => {
  getTreeFilter();
});

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ page: 1, rows: 10, categoryNo: "", loginName: "", userName: "" });

// 获取 treeFilter 数据
// 当 proTable 的 requestAuto 属性为 false，不会自动请求表格数据，等待 treeFilter 数据回来之后，更改 initParam.departmentId 的值，才会触发请求 proTable 数据
const treeFilterData = ref<any>([]);
const getTreeFilter = async () => {
  const data = await getConfigurationCategoryTreeAllData();
  treeFilterData.value = [data];
};
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.page = newParams.pageNum;
  newParams.rows = newParams.pageSize;
  newParams._search = false;
  newParams.sidx = "ciId";
  newParams.sord = "desc";
  delete newParams.pageNum;
  delete newParams.pageSize;
  return cItemsFind(newParams, "ciQueryDTO", ["_search", "sidx", "sord", "page", "rows"]);
};
// 树形筛选切换
const changeTreeFilter = (val: any) => {
  if (val instanceof Array) {
    return;
  }
  if (val == undefined) {
    initParam.categoryNo = "";
    return;
  }
  // 使用traverseTree遍历树
  let newval = JSON.parse(JSON.stringify(val));

  initParam.categoryNo = newval.cno;
  proTable.value!.pageable.pageNum = 1;
  initParam.page = proTable.value!.pageable.pageNum;
  initParam.rows = proTable.value!.pageable.pageSize;
};

// 模拟远程加载性别搜索框数据
const loading = ref(false);
const filterGenderEnum = ref<typeof genderType>([]);
const remoteMethod = (query: string) => {
  filterGenderEnum.value = [];
  if (!query) return;
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    filterGenderEnum.value = genderType.filter(item => item.label.includes(query));
  }, 500);
};

export interface resCIList {
  ciname: string;
  cino: string;
  categoryName: string;
  categoryNo: string;
  status: string;
  owner: string;
  userName: string;
}
// 表格配置项
const columns = reactive<ColumnProps<resCIList>[]>([
  // { type: "index", label: "#", width: 80 },
  { type: "selection", fixed: "left", width: 70 },
  { prop: "owner", label: "负责人", width: 120, isShow: false, search: { el: "input" } },
  { prop: "categoryName", label: "分类" },
  { prop: "cino", label: "编号", width: 120, search: { el: "input" } },
  { prop: "ciname", label: "名称", width: 120, search: { el: "input" } },
  { prop: "status", label: "状态", width: 120 },
  { prop: "operation", label: "操作", width: 100, fixed: "right" }
]);

// 删除用户信息
const deleteAccount = async (params: User.ResUserList) => {
  await useHandleData(deleteUser, { id: [params.id] }, `删除【${params.username}】用户`);
  proTable.value?.getTableList();
};
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  console.log(data.data);
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};

const selfEmit = defineEmits(["sendData"]);
// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const selectOneUser = (data: {}) => {
  //回调数据给父组件
  selfEmit("sendData", [data]);
};

interface TreeNode {
  value: any;
  children?: TreeNode[];
  id: string;
  name: string;
  attr: any;
}

function traverseTree(node: TreeNode, callback: (node: TreeNode) => void) {
  callback(node);
  if (node.children) {
    node.children.forEach(child => traverseTree(child, callback));
  }
}

// 批量选择用户信息
const batchSelectUser = async (data: any) => {
  selfEmit("sendData", data);
};
</script>
